﻿using System.IO;
using System.Web.Routing;
using System.Web.UI;
using SlamCms.Common;
using SlamCms.Web.Mvc;

namespace System.Web.Mvc
{
	public static class HtmlHelperExtensions
	{
		public static IHtmlString Script(this HtmlHelper helper, string fileName)
		{
			return "<script src='{0}' type='text/javascript'></script>".F(SlamCmsUrlHelper.GetScriptUrl(fileName)).ToHtml();
		}

		public static IHtmlString CSS(this HtmlHelper helper, string fileName)
		{
			return CSS(helper, fileName, "screen");
		}

		public static IHtmlString CSS(this HtmlHelper helper, string fileName, string media)
		{
			return "<link rel='stylesheet' type='text/css' href='{0}' media='{1}' />".F(SlamCmsUrlHelper.GetStyleUrl(fileName), media).ToHtml();
		}

		public static IHtmlString Image(this HtmlHelper helper, string fileName, string alt = "", object attributes = null)
		{
			var imageTag = new TagBuilder("img");
			imageTag.MergeAttribute("src", SlamCmsUrlHelper.GetImageUrl(fileName));
			imageTag.MergeAttribute("alt", alt);
			imageTag.MergeAttribute("title", alt);
			//if (!@class.IsNullOrWhiteSpace())
			//    imageTag.AddCssClass(@class);
			var attributesDictionary = new RouteValueDictionary(attributes);
			imageTag.MergeAttributes(attributesDictionary);
			return imageTag.ToString(TagRenderMode.SelfClosing).ToHtml();
		}

		public static HtmlString RenderControl(this HtmlHelper helper, string path)
		{
			return RenderControl<UserControl>(helper, path, null);
		}

		public static HtmlString RenderControl<T>(this HtmlHelper helper, string path) where T : UserControl
		{
			return RenderControl<T>(helper, path, null);
		}

		public static HtmlString RenderControl<T>(this HtmlHelper helper, string path, Action<T> action) where T : UserControl
		{
			var page = new Page();
			T control = (T)page.LoadControl(path);
			page.Controls.Add(control);

			if (action != null)
				action(control);

			using (var sw = new StringWriter())
			{
				HttpContext.Current.Server.Execute(page, sw, false);
				return new HtmlString(sw.ToString());
			}
		}

		public static SlamCmsHtmlHelper SlamCms(this HtmlHelper htmlHelper)
		{
			return new SlamCmsHtmlHelper(htmlHelper);
		}

		public static SlamCmsHtmlHelper<TModel> SlamCms<TModel>(this HtmlHelper<TModel> htmlHelper)
		{
			return new SlamCmsHtmlHelper<TModel>(htmlHelper);
		}

		internal static HtmlHelper<TModel> HtmlHelperForModel<TModel>(this HtmlHelper htmlHelper, TModel model)
		{
			return new HtmlHelper<TModel>(htmlHelper.ViewContext, new ViewDataContainer<TModel>(model));
		}
	}
}
